﻿using log4net;
using MySql.Data.MySqlClient;
using Mysqlx.Crud;
using MySqlX.XDevAPI.Common;
using NewChillers.Helpers;
using NewChillers.Models;
using NewChillers.Models.Events;
using NewChillers.Utils;
using NewChillers.Views;
using SharpVectors.Dom.Svg;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace NewChillers.ViewModels
{
    public class RecipeViewModel : ObservableObject
    {
        private List<RecipeModel> _recipeList; // 配方列表
        private bool _isRecipeListLoading;
        private UserModel _currentUser;
        private readonly ShellViewModel _shellViewModel;
        private string _txtSearch; // 搜索栏

        public List<RecipeModel> RecipeList
        {
            get => _recipeList;
            set => SetProperty(ref _recipeList, value);
        }
        public bool IsRecipeListLoading
        {
            get => _isRecipeListLoading;
            set => SetProperty(ref _isRecipeListLoading, value);
        }
        public string TxtSearch
        {
            get => _txtSearch;
            set => SetProperty(ref _txtSearch, value);
        }

        public ICommand DetailsCommand { get; } // 查看详情
        public ICommand EditCommand { get; } // 编辑
        public ICommand DeleteCommand { get; } // 删除

        public ICommand AddCommand { get; } // 添加配方
        public ICommand RefreshCommand { get; } // 手动刷新列表

        public ICommand SearchCommand { get; } // 查询按钮 模糊搜索

        public RecipeViewModel(UserModel userModel, ShellViewModel shellViewModel)
        {
            _currentUser = userModel;
            _shellViewModel = shellViewModel;

            TxtSearch = ""; // 清空搜索栏
            _ = InitRecipeListAsync();

            DetailsCommand = new RelayCommand<RecipeModel>(ExecuteDetails);
            EditCommand = new RelayCommand<RecipeModel>(ExecuteEdit);
            DeleteCommand = new RelayCommand<RecipeModel>(ExecuteDelete);
            AddCommand = new RelayCommand(ExecuteAdd);
            RefreshCommand = new RelayCommand(ExecuteRefresh);
            SearchCommand = new RelayCommand(ExecuteSearch);

            // 订阅
            _shellViewModel.UserInfoUpdate += OnUserInfoUpdate;
        }

        #region 操作3
        /// <summary>
        /// 模糊搜索
        /// </summary>
        private async void ExecuteSearch(object obj)
        {
            await InitRecipeListAsync();
        }
        #endregion

        #region 操作2
        /// <summary>
        /// 手动刷新列表
        /// </summary>
        private async void ExecuteRefresh(object obj)
        {
            TxtSearch = ""; // 清空搜索栏
            await InitRecipeListAsync();
        }
        /// <summary>
        /// 添加配方 actType == 3
        /// </summary>
        private async void ExecuteAdd(object obj)
        {
            RecipeModel newRecipe = new RecipeModel(); // 添加新的
            try
            {
                // 创建对话框并传值 1:查看详情  2:编辑  3:新增
                var recipeInfoView = new RecipeInfoView(newRecipe, 3, _currentUser);

                // 设置Owner建立窗口关系
                recipeInfoView.Owner = Application.Current.MainWindow;

                // 显示模态对话框并等待结果
                bool? result = recipeInfoView.ShowDialog();

                // 处理对话框返回结果
                if (result == true)
                {
                    Debug.WriteLine("用户进行了 [配方管理]添加配方 操作");

                    // 添加后 从数据库 重新获取配方信息
                    await InitRecipeListAsync();

                    //MsgBoxHelper.Info("添加配方成功，已刷新配方列表"); // 在 RecipeInfoViewModel 里弹窗吧
                    LogHelper.Info(this.GetType(), "[配方管理] | 添加配方成功", _currentUser.UserAccount);
                }
                else if (result == false)
                {
                    // 用户取消了操作
                    Debug.WriteLine("用户取消了 [配方管理]添加配方 操作");
                    await InitRecipeListAsync();
                }
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"打开 [配方管理]添加配方 页面失败: {ex.Message}");
            }
        }
        #endregion

        #region 操作1
        /// <summary>
        /// 删除
        /// </summary>
        private async void ExecuteDelete(RecipeModel selectedRecipe)
        {
            if (selectedRecipe == null)
                return;

            try
            {
                if (MsgBoxHelper.ConfirmYesNo($"确定要删除配方 {selectedRecipe.RecipeName} 吗？"))
                {
                    // DELETE FROM recipe_info WHERE recipe_id = 7
                    string sql = "DELETE FROM recipe_info WHERE recipe_id = @RecipeId";

                    MySqlParameter mySqlParameter = new MySqlParameter("@RecipeId", selectedRecipe.RecipeId);

                    int count = MysqlHelper.ExecuteNonQuery(sql, mySqlParameter);

                    if (count == 1)
                    {
                        await InitRecipeListAsync();

                        Debug.WriteLine("操作 [配方管理]删除 成功");
                        MsgBoxHelper.Info("操作 [配方管理]删除 成功，已刷新配方列表");
                        LogHelper.Info(this.GetType(), "[配方管理] | 删除配方成功" + $" 目标:{selectedRecipe.RecipeId}({selectedRecipe.RecipeName})", _currentUser.UserAccount);
                    }
                    else
                    {
                        MsgBoxHelper.Info("操作 [配方管理]删除 失败，未找到对应配方记录");
                    }
                }
                else
                    Debug.WriteLine("操作 [配方管理]删除 取消");
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"操作 [配方管理]删除 失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 编辑 actType == 2
        /// </summary>
        private async void ExecuteEdit(RecipeModel selectedRecipe)
        {
            if (selectedRecipe == null)
                return;

            try
            {
                // 创建对话框并传值 1:查看详情  2:编辑  3:新增
                var recipeInfoView = new RecipeInfoView(selectedRecipe, 2, _currentUser);

                // 设置Owner建立窗口关系
                recipeInfoView.Owner = Application.Current.MainWindow;

                // 显示模态对话框并等待结果
                bool? result = recipeInfoView.ShowDialog();

                // 处理对话框返回结果
                if (result == true)
                {
                    Debug.WriteLine("用户进行了 [配方管理]编辑 操作");

                    // 编辑后 从数据库 重新获取配方信息
                    await InitRecipeListAsync();

                    // 通知 其他页面 需要吗？

                    //MsgBoxHelper.Success("配方修改成功，已刷新配方列表"); // 在 RecipeInfoViewModel 里弹窗吧
                    LogHelper.Info(this.GetType(), "[配方管理] | 修改配方成功", _currentUser.UserAccount);
                }
                else if (result == false)
                {
                    // 用户取消了操作
                    Debug.WriteLine("用户取消了 [配方管理]编辑 操作");
                    await InitRecipeListAsync();
                }
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"打开 [配方管理]编辑 页面失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 查看详情 actType == 1
        /// </summary>
        private void ExecuteDetails(RecipeModel selectedRecipe)
        {
            if (selectedRecipe == null)
                return;

            try
            {
                // 创建对话框并传值 1:查看详情  2:编辑  3:新增
                var recipeInfoView = new RecipeInfoView(selectedRecipe, 1, _currentUser);

                // 设置Owner建立窗口关系
                recipeInfoView.Owner = Application.Current.MainWindow;

                // 等待结果
                recipeInfoView.ShowDialog();

                // 这是查看详情 没有成功与否 有个关闭就行
                Debug.WriteLine("用户关闭了 [配方管理]查看详情 页面");
            }
            catch (Exception ex)
            {
                MsgBoxHelper.Error($"打开 [配方管理]查看详情 页面失败: {ex.Message}");
            }
        }
        #endregion

        #region 更新当前登录用户的信息 事件处理
        /// <summary>
        /// 接收到通知
        /// </summary>
        private void OnUserInfoUpdate(object sender, UserInfoUpdateEventArgs e)
        {
            // 空值检查，避免NullReferenceException
            if (e?.UpdatedUser != null)
            {
                _currentUser = e.UpdatedUser;
                Debug.WriteLine("Recipe页面 | 用户信息已更新");
            }
            else
            {
                Debug.WriteLine("收到空的事件参数");
            }
        }

        /// <summary>
        /// 析构函数中的事件取消订阅
        /// </summary>
        ~RecipeViewModel()
        {
            _shellViewModel.UserInfoUpdate -= OnUserInfoUpdate;
        }
        #endregion

        #region 显示 RecipeList
        /// <summary>
        /// 显示日志列表
        /// </summary>
        private async Task InitRecipeListAsync()
        {
            // 防止重复加载
            if (IsRecipeListLoading)
                return;

            IsRecipeListLoading = true;

            try
            {
                var recipes = await Task.Run(() =>
                {
                    //string sql = "SELECT * FROM recipe_info ORDER BY recipe_id DESC";
                    string sql = "SELECT * FROM recipe_info ";
                    List<MySqlParameter> parameters = new List<MySqlParameter>();

                    if (!string.IsNullOrEmpty(TxtSearch))
                    {
                        sql += "WHERE recipe_name like @RecipeName ";
                        parameters.Add(new MySqlParameter("@RecipeName", MySqlDbType.VarChar) { Value = "%" + TxtSearch + "%" });
                    }
                    sql += "ORDER BY update_time DESC";

                    Func<IDataRecord, RecipeModel> mapper = reader => new RecipeModel
                    {
                        RecipeId = Convert.ToInt32(reader["recipe_id"]),
                        RecipeName = reader["recipe_name"].ToString(),
                        RecipeProcess = Convert.ToInt32(reader["recipe_process"]),
                        CycleCount = Convert.ToInt32(reader["cycle_count"]),
                        DrawValue = reader["draw_value"].ToString(),
                        DrawKeepTime = Convert.ToInt32(reader["draw_keep_time"]),
                        PumpValue = reader["pump_value"].ToString(),
                        PumpKeepTime = Convert.ToInt32(reader["pump_keep_time"]),
                        VentValue = reader["vent_value"].ToString(),
                        StablePressureValue = reader["stable_pressure_value"].ToString(),
                        StablePressureKeepTime = Convert.ToInt32(reader["stable_pressure_keep_time"]),
                        CreateTime = Convert.ToDateTime(reader["create_time"]),
                        UpdateTime = Convert.ToDateTime(reader["update_time"]),
                        RecipeRemark = reader["recipe_remark"].ToString()
                    };

                    return MysqlHelper.ExecuteQuery<RecipeModel>(sql, mapper, parameters.ToArray());
                });

                RecipeList = recipes;
            }
            catch (Exception ex)
            {
                LogHelper.Error(this.GetType(), "[加载配方] | 配方列表加载失败", ex, _currentUser.UserAccount);
                RecipeList = new List<RecipeModel>();
            }
            finally
            {
                IsRecipeListLoading = false;
            }
        }
        #endregion
    }
}
